package org.example.demoblg.result;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
@Slf4j
public class Jwt {
    public static final long serialVersionUID = 60 * 60 * 60 * 1000;
    public static final String secretString = "dVnsmy+SIX6pNptQdeclDSJ26EMSPEIhvZYKBTTug4k=";
    private static final SecretKey KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String encrypt(Map<String,Object> claim) {
        String token = Jwts.builder()
                .setClaims(claim) //设置载荷信息
                .setExpiration(new Date(System.currentTimeMillis() + serialVersionUID )) //设置过期时间
                .signWith(KEY)  //设置签名
                .compact();
        return token;

    }
    public  static Claims decrypt(String token) {
        if (token==null){
            return null;
        }
        JwtParser build = Jwts.parserBuilder().setSigningKey(KEY).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
//            e.printStackTrace();
            log.error("解析token失败, token:"+token);
        }
        return claims;

    }
    public static Integer idbytoken(String token) {
        Claims claims = decrypt(token);
        if(claims==null){
            return null;
        }
        return  (Integer) claims.get("id");
    }

}
